using UnityEngine;

public static class UiUtil
{


    // 遮挡问题, 视野的显示问题.

    /// <summary>
    /// 将ui 映射到 overleap canvas 的对应位置上。
    /// </summary>
    /// <param name="parentUi">canvas</param>
    /// <param name="rectTrans">锚点需要设置到左下角</param>
    /// <param name="target"></param>
    /// <param name="offset"></param>
    /// <param name="limitInScreen">在屏幕外的点会在屏幕边缘</param>
    public static void UiFowllow(RectTransform parentUi, RectTransform rectTrans, Transform target, Vector2 offset, bool limitInScreen = false)
    {
        var uiPoint = GetPointToUiPosition(parentUi, target.position, limitInScreen);

        rectTrans.localPosition = uiPoint + offset;
    }
    /// <summary>
    /// 返回世界坐标在parent UI 的映射位置
    /// </summary>
    /// <param name="parent"></param>
    /// <param name="rectTrans"></param>
    /// <param name="target"></param>
    /// <returns></returns>
    public static Vector2 GetPointToUiPosition(RectTransform parent, Vector3 target, bool limitInScreen = false ,Vector2 screenScale =default,Camera camera= null)
    {
        camera = camera == null ? Camera.main : camera;
        var screenPoint = RectTransformUtility.WorldToScreenPoint(camera, target);
        if (limitInScreen)
        {
            screenPoint.x = Mathf.Clamp(screenPoint.x, Screen.width* (1-screenScale.x), Screen.width* screenScale.x);
            screenPoint.y = Mathf.Clamp(screenPoint.y, Screen.height *(1-screenScale.y), Screen.height* screenScale.y);
        }
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, screenPoint, null, out var vector2))
        {
            return vector2;
        }
        return Vector2.zero;
    }
    private static Rect ViewProtRect { get; } = new Rect(0f, 0f, 1f, 1f);
    private static bool IsTargetInScreen(Transform target)
    {
        var MainCamera = Camera.main;
        // 转换目标的世界坐标至屏幕坐标
        var point = MainCamera.WorldToViewportPoint(target.position);

        // 屏幕坐标的z值处于相机的进截面和远截面之间，并且处于屏幕范围内，即表示锁定对象在可视范围内
        var isInScreen = point.z > MainCamera.nearClipPlane && point.z < MainCamera.farClipPlane && ViewProtRect.Contains(point);

        return isInScreen;
    }
}
